// 云对象教程: https://uniapp.dcloud.net.cn/uniCloud/cloud-obj
// jsdoc语法提示教程：https://ask.dcloud.net.cn/docs/#//ask.dcloud.net.cn/article/129
let request = require('request');
let UserAgent = require('user-agents');
let cheerio = require('cheerio'); //爬虫
let iconv = require('iconv-lite'); //处理gbk编码的网页
module.exports = {
	_before: function() { // 通用预处理器

	},

	/**
	 * 获取姓氏起源
	 * @param {Object} namepy
	 */
	getXingData(namepy) {
		const userAgent = new UserAgent().toString();
		console.log('---- getXingData ----:', userAgent, namepy);
		return new Promise((resolve, reject) => {
			request({
				url: `https://baijiaxing.bmcx.com/${namepy}__baijiaxing/`,
				headers: {
					'User-Agent': userAgent
				}
				// encoding: null //设置抓取页面时不要对数据做任何转换
			}, function(err, res, body) {
				// console.log('---- getToolsData xing ----:', typeof body, body);
				if (err) {
					reject(err)
				} else {
					// console.log('---- getTrainStationStation ----:', body);
					try {
						var $ = null;
						$ = cheerio.load(body);
						let resultData = [];
						//兼容网页编码格式
						if ($('meta[charset]').attr('charset') == 'utf-8') { //如果网页是utf-8的编码
						} else { //如果网页是gbk的编码
							body = iconv.decode(body, 'gbk'); //转换gbk编码的页面内容
							$ = cheerio.load(body);
						}
						console.log('---- html ----:', $('.mod-table').html());
						const html = $('.neirong').html();
						resolve(html ? html : null);
					} catch (e) {
						//TODO handle the exception
						resolve(null);
					}
				}
			}, {
				verify: false
			});
		})
	}
}